// pages/blocks/blocks.js 
// 所有名片组
const utils = require('../../utils/util.js')

Page({
  data:{
    list1: [],
    list2: [],
    editorShow: false,
    chunkName: ""
  },
  ...utils.defaultShare,
  onShow() {
    this.getAllChunkList()
  },
  getAllChunkList() {
    utils
      .ajax("/v1/bcs/queryUserCardHolderGroups.do", {
        cardId: this.data.cardId
      })
      .then(res => {
        if (res.code === "000000") {
          let list1 = [], list2 = [];
          try{
            list1 = res.data.catetories[0].groups
          }catch(e){
            list1 = [];
          }
          try {
            list2 = res.data.catetories[1].groups
          } catch (e) {
            list2 = [];
          }
          this.setData({
            list1,
            list2
          })
        } else {
          console.log(res.message || "获取标签失败");
        }
      })
      .catch(res => { });
  },
  showBlockEditor() {
    this.setData({
      editorShow: true
    })
  },
  editorCancel() {
    this.setData({
      editorShow: false
    })
  },
  editorConfirm() {
    // 发送请求，并把结果添加到list1中
    utils
      .ajax("/v1/bcs/createUserCardHolderGroup.do", {
        name: this.data.chunkName
      })
      .then(res => {
        if (res.code === "000000") {
          const list = [...this.data.list1, { name: this.data.chunkName, count: 0, groupId: res.data.groupId }]
          this.setData({
            editorShow: false,
            chunkName: '',
            list1: list
          })
        } else {
          console.log(res.message || "获取标签失败");
        }
      })
      .catch(res => { });
  },
  chunkNameChangeEvent(event) {
    const value = event.detail.value;
    this.setData({
      chunkName: value
    })
  },
  deletGroup(event){
    const groupId = event.currentTarget.dataset.id;
    console.log(groupId)
    const _this = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除该分组吗',
      success(res){
        if(res.confirm){
          utils
            .ajax("/v1/bcs/delUserCardHolderGroup.do", {
              groupId,
            })
            .then(res => {
              if (res.code === "000000") {
                let list = _this.data.list1.filter(item => {
                  return item.groupId != groupId
                })
                _this.setData({
                  list1: list
                })
              } else {
                console.log(res.message || "删除分组失败，请稍后再试"); 
                utils.message(res.message || "删除分组失败，请稍后再试"); 
              }
            })
            .catch(res => { });
        }
      }
    })
  }
})